package Pet.Management.controller;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import Pet.Management.domain.entity.Comment;
import Pet.Management.domain.entity.Like;
import Pet.Management.domain.entity.Post;
import Pet.Management.domain.entity.User;
import Pet.Management.repository.CommentRepository;
import Pet.Management.repository.LikeRepository;
import Pet.Management.repository.PostRepository;
import Pet.Management.repository.UserRepository;
import Pet.Management.service.MessageService;

@RestController
@RequestMapping("/api/comments")
public class CommentController {

    @Autowired
    private CommentRepository commentRepository;
    
    @Autowired
    private PostRepository postRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private LikeRepository likeRepository;
    
    @Autowired
    private MessageService messageService;
    
    /**
     * 获取帖子的评论列表
     */
    @GetMapping("/post/{postId}")
    public ResponseEntity<Map<String, Object>> getCommentsByPost(
            @PathVariable Long postId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        Optional<Post> postOpt = postRepository.findById(postId);
        if (!postOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Comment> commentPage = commentRepository.findRootCommentsByPostId(postId, pageable);
        
        List<Map<String, Object>> comments = commentPage.getContent().stream().map(comment -> {
            Map<String, Object> commentMap = Map.of(
                "id", comment.getId(),
                "content", comment.getContent(),
                "author", Map.of(
                    "id", comment.getUser().getId(),
                    "username", comment.getUser().getUsername(),
                    "nickname", comment.getUser().getNickname(),
                    "avatar", comment.getUser().getAvatar()
                ),
                "likeCount", comment.getLikeCount(),
                "createTime", comment.getCreateTime(),
                "isLiked", isCommentLikedByUser(comment.getId(), token)
            );
            
            // 获取评论的回复
            List<Comment> replies = commentRepository.findRepliesByParentId(comment.getId());
            
            List<Map<String, Object>> replyList = replies.stream().map(reply -> 
                Map.of(
                    "id", reply.getId(),
                    "content", reply.getContent(),
                    "author", Map.of(
                        "id", reply.getUser().getId(),
                        "username", reply.getUser().getUsername(),
                        "nickname", reply.getUser().getNickname(),
                        "avatar", reply.getUser().getAvatar()
                    ),
                    "likeCount", reply.getLikeCount(),
                    "createTime", reply.getCreateTime(),
                    "isLiked", isCommentLikedByUser(reply.getId(), token)
                )
            ).collect(Collectors.toList());
            
            return Map.of(
                "comment", commentMap,
                "replies", replyList
            );
        }).collect(Collectors.toList());
        
        return ResponseEntity.ok(Map.of(
            "comments", comments,
            "currentPage", commentPage.getNumber(),
            "totalItems", commentPage.getTotalElements(),
            "totalPages", commentPage.getTotalPages()
        ));
    }
    
    /**
     * 添加评论
     */
    @PostMapping("/post/{postId}")
    @Transactional
    public ResponseEntity<Comment> addComment(
            @PathVariable Long postId,
            @RequestBody Map<String, String> payload,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        if (token == null || token.isEmpty()) {
            return ResponseEntity.status(401).build();
        }
        
        // 这里简单处理，假设token就是username
        Optional<User> currentUser = userRepository.findByUsername(token);
        if (!currentUser.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<Post> postOpt = postRepository.findById(postId);
        if (!postOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        String content = payload.get("content");
        String parentIdStr = payload.get("parentId");
        
        Comment comment = new Comment();
        comment.setContent(content);
        comment.setPost(postOpt.get());
        comment.setUser(currentUser.get());
        
        // 如果是回复其他评论
        if (parentIdStr != null && !parentIdStr.isEmpty()) {
            try {
                Long parentId = Long.parseLong(parentIdStr);
                Optional<Comment> parentComment = commentRepository.findById(parentId);
                if (parentComment.isPresent()) {
                    comment.setParent(parentComment.get());
                }
            } catch (NumberFormatException e) {
                // 忽略无效的parentId
            }
        }
        
        Comment savedComment = commentRepository.save(comment);
        
        // 发送评论通知
        messageService.sendCommentNotification(savedComment);
        
        // 更新帖子的评论数
        postRepository.updateCommentCount(postId, 1);
        
        return ResponseEntity.ok(savedComment);
    }
    
    /**
     * 点赞/取消点赞评论
     */
    @PostMapping("/{commentId}/like")
    @Transactional
    public ResponseEntity<Map<String, Object>> likeComment(
            @PathVariable Long commentId,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        if (token == null || token.isEmpty()) {
            return ResponseEntity.status(401).build();
        }
        
        // 这里简单处理，假设token就是username
        Optional<User> currentUser = userRepository.findByUsername(token);
        if (!currentUser.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<Comment> commentOpt = commentRepository.findById(commentId);
        if (!commentOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Comment comment = commentOpt.get();
        User user = currentUser.get();
        
        Optional<Like> existingLike = likeRepository.findByUserIdAndCommentId(user.getId(), comment.getId());
        boolean isLiked;
        
        if (existingLike.isPresent()) {
            // 取消点赞
            likeRepository.delete(existingLike.get());
            commentRepository.updateLikeCount(comment.getId(), -1);
            isLiked = false;
        } else {
            // 点赞
            Like like = new Like();
            like.setUser(user);
            like.setComment(comment);
            likeRepository.save(like);
            commentRepository.updateLikeCount(comment.getId(), 1);
            isLiked = true;
        }
        
        // 重新获取最新的点赞数
        comment = commentRepository.findById(commentId).get();
        
        return ResponseEntity.ok(Map.of(
            "likeCount", comment.getLikeCount(),
            "isLiked", isLiked
        ));
    }
    
    /**
     * 判断评论是否被当前用户点赞
     */
    private boolean isCommentLikedByUser(Long commentId, String token) {
        if (token == null || token.isEmpty()) {
            return false;
        }
        
        // 这里简单处理，假设token就是username
        Optional<User> currentUser = userRepository.findByUsername(token);
        if (!currentUser.isPresent()) {
            return false;
        }
        
        Optional<Like> like = likeRepository.findByUserIdAndCommentId(currentUser.get().getId(), commentId);
        return like.isPresent();
    }

    @PostMapping("/{commentId}/reply")
    @Transactional
    public ResponseEntity<Comment> addReply(
            @PathVariable Long commentId,
            @RequestBody Map<String, String> payload,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        // 验证用户
        if (token == null || token.isEmpty()) {
            return ResponseEntity.status(401).build();
        }
        
        User user;
        try {
            // 尝试将token解析为用户ID
            Long userId = Long.parseLong(token);
            Optional<User> currentUser = userRepository.findById(userId);
            
            if (!currentUser.isPresent()) {
                return ResponseEntity.status(401).build();
            }
            user = currentUser.get();
        } catch (NumberFormatException e) {
            // 如果token不是有效的用户ID，尝试按用户名查找
            Optional<User> currentUser = userRepository.findByUsername(token);
            if (!currentUser.isPresent()) {
                return ResponseEntity.status(401).build();
            }
            user = currentUser.get();
        }
        
        // 验证父评论是否存在
        Optional<Comment> parentCommentOpt = commentRepository.findById(commentId);
        if (!parentCommentOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Comment parentComment = parentCommentOpt.get();
        
        // 创建回复
        Comment reply = new Comment();
        reply.setUser(user);
        reply.setPost(parentComment.getPost());
        reply.setContent(payload.get("content"));
        reply.setParent(parentComment);
        
        Comment savedReply = commentRepository.save(reply);
        
        // 发送回复通知
        messageService.sendReplyNotification(savedReply, parentComment);
        
        // 更新帖子的评论数
        postRepository.updateCommentCount(parentComment.getPost().getId(), 1);
        
        return ResponseEntity.ok(savedReply);
    }
} 